package com.brewster.controller.index;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;

import com.brewster.config.model.Account;
import com.brewster.config.shiro.ShiroTag;
import com.jfinal.aop.Clear;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;

/**
 * 本 demo 仅表达最为粗浅的 jfinal 用法，更为有价值的实用的企业级用法 详见 JFinal 俱乐部:
 * http://jfinal.com/club
 * 
 * IndexController
 */

public class IndexService extends Controller {

	public void index() {
		render("index.html");
	}

	public void doLogin() {
		String username = getPara("account");
		String password = getPara("password");

		Subject currentUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		try {
			currentUser.login(token);
			Account loginAccount = (Account) SecurityUtils.getSubject().getPrincipal();
			System.out.println(loginAccount);
			if (loginAccount.getInt("del_flag") == 9) {
				renderFail("账户已经禁用");
				return;
			}

//			onlineListener(getRequest());
			renderJson(Ret.ok());
		} catch (UnknownAccountException exception) {
			renderFail("账户不存在");
		} catch (IncorrectCredentialsException exception) {
			renderFail("账户或者密码错误");
		} catch (LockedAccountException exception) {
			renderFail("账号被锁定");
		}

	}

	@RequiresAuthentication
	@RequiresPermissions({ "archive:down" })
	public void test1() {
		Account loginAccount = (Account) SecurityUtils.getSubject().getPrincipal();
		System.out.println(loginAccount);
		renderJson(loginAccount);
	}

	@RequiresAuthentication
	@RequiresPermissions({ "archive:down" })
	public void test2() {
		ShiroTag shiro = new ShiroTag();
		System.out.println(shiro.hasPermission("archives:manage"));
		System.out.println(shiro.hasPermission("archives:manage2"));
	}

	public void test3() {
		render("/blog/blog.html");
	}

	private void renderFail(String string) {
		renderJson(Ret.ok("msg", string));
	}

	/**
	 * 退出登录
	 */
	@Clear
	@ActionKey("/logout")
	public void logout() {
		SecurityUtils.getSubject().logout();
		//redirect("http://192.168.1.75:8082/login");
		redirect("/");
	}
}
